import { exceedAuthority } from '@/global-utils/base.utils';

const store = {
	// 当前store的 id 标识
	name: 'WebSocketStore',
	function: (): any => {
		const SocketState = reactive<TsWebsocket>({
			ws: null,
			isConnected: true,
			retryCount: 0,
			maxRetries: 10,
			retryInterval: 5000,
			reTimer: null,
			heartbeatTimer: null,
			noAuthPathList: ['/login', '/404', '/403', '/']
		});
		const route = useRoute();

		/**
		 *
		 * @param message 发送的消息体
		 */
		const ScoketSend = (message: any): void => {
			let timer: any = null;
			clearTimeout(timer);
			timer = setTimeout(() => {
				// 判断当前的连接状态
				if (SocketState.ws.readyState === WebSocket.OPEN) {
					SocketState.ws.send(JSON.stringify(message));
				} else {
					// console.log('WebSocket未连接');
				}
			}, 200);
		};
		// socket 连接

		const _socketConnect = (): void => {
			const token = window.sessionStorage.getItem('token');
			console.log(import.meta.env.MODE, 2222222222222);
			SocketState.ws = new WebSocket(
				`ws://${import.meta.env.MODE === 'development' ? '192.168.16.9:30845' : window.location.host}/websocket/${token}`
				// `ws://${import.meta.env.MODE === 'development' ? '192.168.15.55:18011' : window.location.host}/websocket/${token}`
			); // 测试
			SocketState.isConnected = true;
			// 连接成功触发
			SocketState.ws.onopen = (): void => {
				console.log('连接成功', window.location.host);
				SocketState.retryCount = 0; // 重置重试次数
				if (SocketState.heartbeatTimer) {
					clearTimeout(SocketState.heartbeatTimer);
				}
				// 发送心跳包 维持连接
				SocketState.heartbeatTimer = setInterval(() => {
					ScoketSend({ heartbeat: 1 });
				}, 10000);
			};

			SocketState.ws.onmessage = (info: any): void => {
				const obj = JSON.parse(info.data);
				exceedAuthority(obj);
			};

			// 连接时报错
			SocketState.ws.onerror = (error: any): void => {
				console.error(`WebSocket error1: ${error}`);
			};

			// 断开连接时触发
			SocketState.ws.onclose = (): void => {
				console.log('关闭连接');

				if (SocketState.heartbeatTimer) {
					clearTimeout(SocketState.heartbeatTimer);
				}
				if (SocketState.isConnected) {
					SocketState.retryCount++;
					if (SocketState.reTimer) {
						clearTimeout(SocketState.reTimer);
					}
					// 小于等于最大连接次数 就尝试重连
					if (SocketState.retryCount <= SocketState.maxRetries) {
						SocketState.reTimer = setTimeout(() => {
							// console.log('执行重连');
							_socketConnect(); // 重新执行
							SocketState.reTimer = null;
						}, SocketState.retryInterval);
					}
				}
			};
		};
		/**
		 *  websocket 连接重连
		 */
		const F_ConnectSocket = (): void => {
			watchEffect(() => {
				const flag =
					!SocketState.noAuthPathList.includes(route.path) &&
					(!SocketState.ws || (SocketState.ws && SocketState.ws.readyState !== WebSocket.OPEN));
				if (flag) {
					_socketConnect();
				} else if (route.path === '/login' && SocketState.ws && SocketState.ws.readyState === WebSocket.OPEN) {
					SocketState.isConnected = false; // 禁止重连
					SocketState.ws.close(); // 断开连接
				}
			});
		};

		return { SocketState, ScoketSend, F_ConnectSocket };
	}
};

export { store };
